package cc.opcol.iot.server.sdk;

import cc.opcol.iot.server.util.CRC16Util;
import cc.opcol.iot.server.util.HexUtil;
import cc.opcol.iot.server.util.OpcolUtil;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

@Component
public class ScriptEngineHelper {
    static Logger logger= LoggerFactory.getLogger(ScriptEngineHelper.class);
    @Autowired
    JSEntityAgent jsEntityAgent;

    @Autowired
    JSRepositoryAgent jsRepositoryAgent;

    @Autowired
    JSTimerManager jsTimerManager;

    @Autowired
    SpringBeanHelper springBeanHelper;

    @Autowired
    MongoTemplate mongoTemplate;

    public ScriptEngine createJsEngine() {
        ScriptEngine jsEngine=new ScriptEngineManager().getEngineByExtension("js");
        jsEngine.put("JSLogger",logger);
        jsEngine.put("JSRepository",jsRepositoryAgent);
        jsEngine.put("JSEntity",jsEntityAgent);
        jsEngine.put("JScrc16",new CRC16Util());
        jsEngine.put("JSTimer",jsTimerManager);
        jsEngine.put("JContext",jsEngine);
        jsEngine.put("Json",new Gson());
        jsEngine.put("JSBean",springBeanHelper);
        jsEngine.put("JSHexUtil", HexUtil.getInstance());
        jsEngine.put("JSdb",mongoTemplate);
        jsEngine.put("JSopUtil", OpcolUtil.instance);
        return jsEngine;
    }
}
